""" 

    Data.py used in RepresentedBy Facebook application
    http://apps.facebook.com/representedby/
    
    This script is only meant for admin purposes.
    
    Some of the functions I wanted to build required a lot of API calls to information
    that really doesn't change very often.  This function allows me to visit one CPU intensive URL,
    and then cut/paste the output and put it into the const library.
    
    Yeah, it's a hack, but the optimization was definitely worth the hassle of updating the const
    library periodically.
    
"""

__author__ = "Will Turnage (will @t wubbahed d0t com)"
__version__ = "0.1.0"
__copyright__ = "Copyright (c) 2009 wubbahed.com"
__license__ = "GPLv3"

import const
import os
import wsgiref.handlers

from django.utils import simplejson
from xml.dom import minidom

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from sets import Set

from utils import SunlightUtil, memcacheUtil
        
class MainHandler(webapp.RequestHandler):

    def get(self):

        reps_bio = []
        senators_bio = []
        legislators_by_state = {}
        friendly_name = {}
        govtrack = {}
        committees = {}
        committee_by_member = {}
        committee_by_chair = {}
        
        parties = {"D":[], "R":[]}
        features = { "twitter_id": [], "official_rss": [], "email": [], "youtube_url": [] }
            
        sunlight = SunlightUtil(const.SUNLIGHT_API_KEY)
        congress = sunlight.apicall('legislators.getList')
        
        if congress is not None:

            for legislator in congress["legislators"]:
                govtrack[legislator["legislator"]["govtrack_id"]] = legislator["legislator"]
                if legislator["legislator"]["nickname"] == "":
                    friendly_name[legislator["legislator"]["bioguide_id"]] = legislator["legislator"]["firstname"] + " " + legislator["legislator"]["lastname"]
                else:
                    friendly_name[legislator["legislator"]["bioguide_id"]] = legislator["legislator"]["nickname"] + " " + legislator["legislator"]["lastname"]
  
                if not legislators_by_state.has_key(legislator["legislator"]["state"]):
                    legislators_by_state[legislator["legislator"]["state"]] = {"senators":[], "representatives":[]}
                                      
                if legislator["legislator"]["title"] == "Sen":
                    senators_bio.append(legislator["legislator"]["bioguide_id"])
                    legislators_by_state[legislator["legislator"]["state"]]["senators"].append(legislator["legislator"]["bioguide_id"])
                else:
                    reps_bio.append(legislator["legislator"]["bioguide_id"])
                    legislators_by_state[legislator["legislator"]["state"]]["representatives"].append(legislator["legislator"]["bioguide_id"])

                for party in parties.keys():
                    if legislator["legislator"].has_key("party"):
                        if legislator["legislator"]["party"] is not None and legislator["legislator"]["party"] != "":
                            if parties.has_key(legislator["legislator"]["party"]):
                                if legislator["legislator"]["party"] == party:
                                    parties[legislator["legislator"]["party"]].append(legislator["legislator"]["bioguide_id"])
                                
                for feature in features.keys():
                    if legislator["legislator"].has_key(feature):
                        if legislator["legislator"][feature] is not None and legislator["legislator"][feature] != "":
                            features[feature].append(legislator["legislator"]["bioguide_id"])
                    
            result = memcacheUtil().getTextFromCache(const.GOVTRACK_DATA_URL + const.CURRENT_CONGRESS + "/committees.xml")
            xmlobj = minidom.parseString(result)
            committeesXML = xmlobj.getElementsByTagName("committee")

            for committee in committeesXML:
                if committee.getAttribute("obsolete") != "1":
                    tempDict = {}
                    tempDict["name"] = (committee.getAttribute("displayname"))
                    tempDict["members"] = []
                    members = committee.getElementsByTagName("member")
                    for member in members:
                        tempMem = member.getAttribute("id")
                        if govtrack.has_key(tempMem):
                            bio_id = govtrack[tempMem]["bioguide_id"]
                            tempDict["members"].append(bio_id)
                            if not committee_by_member.has_key(bio_id):
                                committee_by_member[bio_id] = []
                            committee_by_member[bio_id].append(committee.getAttribute("code"))
                            if member.getAttribute("role") == "Chairman":
                                tempDict["chairman"] = bio_id
                                if not committee_by_chair.has_key(bio_id):
                                    committee_by_chair[bio_id] = []
                                committee_by_chair[bio_id].append(committee.getAttribute("code"))
                    committees[committee.getAttribute("code")] = tempDict
                    
        
        self.response.out.write("LEGISLATORS_BY_STATE=" + str(legislators_by_state) + "\n")
        self.response.out.write("FRIENDLY_NAME=" + str(friendly_name) + "\n")
        self.response.out.write("REPRESENTATIVES=" + str(reps_bio) + "\n")
        self.response.out.write("SENATORS=" + str(senators_bio) + "\n")
        self.response.out.write("PARTY_AFFILIATIONS=" + str(parties) + "\n")
        self.response.out.write("LEGISLATOR_ATTR=" + str(features) + "\n")
        
        self.response.out.write("COMMITTEES=" + str(committees) + "\n")
        self.response.out.write("COMMITTEE_BY_MEMBER=" + str(committee_by_member) + "\n")
        self.response.out.write("COMMITTEE_BY_CHAIR=" + str(committee_by_chair) + "\n")
        

def main():
    application = webapp.WSGIApplication([('/fb/data', MainHandler)],
                                       debug=True)
    run_wsgi_app(application)
                                       

if __name__ == '__main__':
    main()
